package org.zjx.dubbo;

import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.ReferenceConfig;

import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DubboServiceFactory {
    private static final Map<Class<?>, Object> SERVICE_CACHE = new ConcurrentHashMap<>();
    private static final ApplicationConfig APPLICATION_CONFIG = new ApplicationConfig(
            ConfigUtils.getProperty("dubbo.application.name")
    );

    // 全局 Consumer 配置（可选）
    private static final ConsumerConfig CONSUMER_CONFIG = new ConsumerConfig();
    static {
        CONSUMER_CONFIG.setTimeout(Integer.parseInt(
                ConfigUtils.getProperty("dubbo.consumer.timeout", "3000")
        ));
        CONSUMER_CONFIG.setRetries(Integer.parseInt(
                ConfigUtils.getProperty("dubbo.consumer.retries", "2")
        ));
        // 通过parameters设置序列化方式
        CONSUMER_CONFIG.setParameters(Collections.singletonMap("serialization", "fastjson2"));
        APPLICATION_CONFIG.setSerializeCheckStatus("DISABLE");
    }

    /**
     * 获取服务实例
     * @param serviceInterface 服务接口类
     * @param serviceKey 配置文件中服务 URL 的 key（如 "user.service.url"）
     */
    @SuppressWarnings("unchecked")
    public static <T> T getService(Class<T> serviceInterface, String serviceKey) {
        T service = (T) SERVICE_CACHE.get(serviceInterface);
        if (service != null) {
            return service;
        }

        ReferenceConfig<T> reference = new ReferenceConfig<>();
        reference.setApplication(APPLICATION_CONFIG);
        reference.setInterface(serviceInterface);
        reference.setUrl(ConfigUtils.getProperty(serviceKey)); // 从配置读取 URL
        reference.setConsumer(CONSUMER_CONFIG); // 设置全局 Consumer 配置
        // 通过parameters设置序列化方式
        reference.setParameters(Collections.singletonMap("serialization", "fastjson"));

        service = reference.get();
        SERVICE_CACHE.put(serviceInterface, service);
        return service;
    }
}